package ij.plugin.filter;
import ij3d.geom.ObjectCreator3D;

import ij.*;
import ij.measure.*;
import ij.plugin.filter.*;
import ij.process.*;
import ij3d.geom.Object3D;

import java.text.*;

/**
 *  plugin to fit an 3D ellipsoid to a shape
 *
 * @author     Thomas BOUDIER
 * @created    avril 2003
 */
public class Axes3D_ implements PlugInFilter {
	ImagePlus imp;
	float rad;
	public Axes3D_(ImagePlus imp1){
		this.imp=imp1;
	}

	private double getMaxFromImageStack(ImagePlus imp){
		ImageProcessor ip;
		double max=0;
		ImageStack imst=imp.getImageStack();
		for (int i = 1; i <= imst.getSize(); i++) {
			ip=imst.getProcessor(i);
			if(ip.getMax()>max)
				max=ip.getMax();

		}
		System.out.println("Maxxx   "+max);
		return max;
	}

	/**
	 *  Main processing method for the Axes3D_ object
	 *
	 * @param  ip  Description of the Parameter
	 */
	@Override
	public void run(ImageProcessor ip) {
		Calibration cal = imp.getCalibration();
		double resXY = 1.0;
		double resZ = 1.0;
		String unit = "pix";
		if (cal != null) {
			if (cal.scaled()) {
				resXY = cal.pixelWidth;
				resZ = cal.pixelDepth;
				unit = cal.getUnits();
			}
		}
		//drawing of ellipses
		ObjectCreator3D ellipsoid = new ObjectCreator3D(imp.getWidth(), imp.getHeight(), imp.getStackSize());
		ellipsoid.setResolution(resXY, resZ, unit);
		Object3D obj;
		// all objects from count masks
		
		//**int valmax=(int)ip.getMax();
		
		double valmax=getMaxFromImageStack(imp);
		for (int val = 1; val <= valmax; val++) {
			IJ.showStatus("obj " + val);
			obj = new Object3D(imp, val);
		//**	obj.computeBounding();
		//**	obj.computeCenter();


			NumberFormat nf = NumberFormat.getInstance();
			nf.setMaximumFractionDigits(3);

			if (obj.getVolumePixels() > 0) {
				obj.computeMoments();
				for (int i = 0; i < 3; i++) {
					IJ.log(val + ": Vector " + i + " : " + obj.getVectorAxis(i));
					IJ.log(val + ": Value  " + i + " : " + nf.format(obj.getValueAxis(i)));
				}

				obj.computeContours();
				double rad1 = obj.getDistCenterMax();
				double rad2 = rad1 / obj.getMainElongationAxis();
				double rad3 = rad2 / obj.getMedianElongationAxis();
				IJ.log(val + ": radii=" + nf.format(rad1) + " " + nf.format(rad2) + " " + nf.format(rad3));
				ellipsoid.createEllipsoidAxes((int) obj.getCenterX(), (int) obj.getCenterY(), (int) obj.getCenterZ(), rad1/resXY, rad2/resXY, rad3/resZ, val, obj.getMatrixAxes(), false);
			}
		}
		new ImagePlus("Ellipsoides"+imp.getID(), ellipsoid.getStack()).show();
	}

	/**
	 *  Description of the Method
	 *
	 * @param  arg  Description of the Parameter
	 * @param  imp  Description of the Parameter
	 * @return      Description of the Return Value
	 */
	@Override
	public int setup(String arg, ImagePlus imp) {
		this.imp = imp;
		return DOES_8G + DOES_16 + NO_CHANGES;
	}
}

